package com.zlkj.pro.core.security.validate;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.auth.api.exception.AuthException;
import cn.stylefeng.roses.kernel.config.api.context.ConfigContext;
import cn.stylefeng.roses.kernel.jwt.JwtTokenOperator;
import cn.stylefeng.roses.kernel.jwt.api.JwtApi;
import cn.stylefeng.roses.kernel.jwt.api.exception.JwtException;
import cn.stylefeng.roses.kernel.jwt.api.exception.enums.JwtExceptionEnum;
import cn.stylefeng.roses.kernel.jwt.api.pojo.config.JwtConfig;
import com.zlkj.pro.core.exception.enums.BusinessExceptionEnum;
import org.springframework.stereotype.Service;

import static cn.stylefeng.roses.kernel.auth.api.exception.enums.AuthExceptionEnum.AUTH_EXPIRED_ERROR;
import static cn.stylefeng.roses.kernel.auth.api.exception.enums.AuthExceptionEnum.TOKEN_PARSE_ERROR;

@Service
public class ValidateTokenServiceImpl implements ValidateTokenServiceApi {

    @Override
    public void checkAuth(String token, String requestUrl) {

        // 1. 校验token是否传参
        if (StrUtil.isEmpty(token)) {
            throw new AuthException(BusinessExceptionEnum.LOGIN_IS_INVALID_PLEASE_LOG_IN_AGAIN);
        }

        // 2. 校验用户token是否正确，校验失败会抛出异常
        this.validateToken(token);

    }

    /**
     * 校验用户是否认证通过，认证是校验token的过程，校验失败会抛出异常
     *
     * @param token 用户登陆的token
     * @author fengshuonan
     * @date 2020/10/22 16:03
     */
    @Override
    public void validateToken(String token) throws AuthException {
        //校验是否该token在异地登录

        try {
            // 1. 先校验jwt token本身是否有问题
            JwtConfig jwtConfig = new JwtConfig();
            jwtConfig.setJwtSecret(ConfigContext.me().getConfigValueNullable("BUSINESS_API_JWT_SECRET", String.class));
            jwtConfig.setExpiredSeconds(ConfigContext.me().getConfigValueNullable("BUSINESS_API_JWT_EXPIRED_SECONDS", Long.class));
            JwtApi jwtApi = new JwtTokenOperator(jwtConfig);
            jwtApi.validateTokenWithException(token);

            // 2. 判断session里是否有这个token
//            LoginUser session = sessionManagerApi.getSession(token);
//            if (session == null) {
//                throw new AuthException(AUTH_EXPIRED_ERROR);
//            }
        } catch (JwtException jwtException) {
            // jwt token本身过期的话，返回 AUTH_EXPIRED_ERROR
            if (JwtExceptionEnum.JWT_EXPIRED_ERROR.getErrorCode().equals(jwtException.getErrorCode())) {
                throw new AuthException(AUTH_EXPIRED_ERROR);
            } else {
                // 其他情况为返回jwt解析错误
                throw new AuthException(TOKEN_PARSE_ERROR);
            }
        } catch (io.jsonwebtoken.JwtException jwtSelfException) {
            // 其他jwt解析错误
            throw new AuthException(TOKEN_PARSE_ERROR);
        }
    }

}
